<?php
	require_once('./config.php');
	require_once('./network.php');
	require_once('./security.php');

	$token=GetToken();

	if(!$token)
	{
		$error='Need Authorization';//错误信息:需要验证
		FailFeed($error);
	}
	else
	{
		$response=GetFeed($token);
		
		if($response['http_code']==200)
		{
			header('Content-Type: '. $response['content_type']);
			print($response['content']);
		}
		else
		{
			$error=$response['http_code'] . '<br />' . htmlentities($response['content'], ENT_QUOTES, 'UTF-8', FALSE);
			FailFeed($error);
		}
	}

	function FailFeed($error)//Feed输出错误信息
	{
		global $base_url;

		$time=gmdate('r');
		$output="<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<rss version=\"2.0\">\r\n<channel>\r\n<title>Twitter Feed</title>\r\n<link>$base_url</link>\r\n<pubDate>$time</pubDate>\r\n<language>en-us</language>\r\n<item>\r\n<title>Twitter Feed Error</title>\r\n<description>\r\n<![CDATA[\r\n$error\r\n]]>\r\n</description>\r\n<pubDate>$time</pubDate>\r\n<guid>$time</guid>\r\n<link>$base_url</link>\r\n</item>\r\n</channel>\r\n</rss>\r\n";

		header('Content-Type: application/rss+xml; charset=utf-8');
		print($output);

		return 0;
	}

	function GetFeed($token)
	{
		global $oauth_signature_method, $oauth_version, $api_url, $consumer_key, $consumer_secret;

		$oauth_timestamp=time();
		$oauth_nonce=$oauth_timestamp;

		$oauth_param=array('oauth_consumer_key'=>$consumer_key, 'oauth_token'=>$token['oauth_token'], 'oauth_signature_method'=>$oauth_signature_method, 'oauth_timestamp'=>$oauth_timestamp, 'oauth_nonce'=>$oauth_nonce, 'oauth_version'=>$oauth_version);
		foreach($oauth_param as $key => $val)
			$oauth_param[$key]=urlencode($val);

		$method='GET';

		$url=$api_url;
		if(isset($_GET['type']) && $_GET['type']=='mentions')
			$url .= 'statuses/mentions';
		else
			$url .= 'statuses/home_timeline';
		if(isset($_GET['fmt']) && $_GET['fmt']=='atom')
			$url .= '.atom';
		else
			$url .= '.rss';
		
		$secret=$consumer_secret . '&' . $token['oauth_token_secret'];

		$qurry_param=NULL;
		//处理Feed参数,需要urlncode
		if(isset($_GET['since_id']))
			$qurry_param['since_id']=$_GET['since_id'];
		if(isset($_GET['max_id']))
			$qurry_param['max_id']=$_GET['max_id'];
		if(isset($_GET['count']))
			$qurry_param['count']=$_GET['count'];
		if(isset($_GET['page']))
			$qurry_param['page']=$_GET['page'];
		if($qurry_param!=NULL)
			foreach($qurry_param as $key => $val)
			$qurry_param[$key]=urlencode($val);

		$response=TwitterHttp($method, $url, $oauth_param, $secret, $qurry_param);

		return $response;
	}
?>